/**
 * Project Reactor
 */


#include "TcpConnection.h"

/**
 * TcpConnection implementation
 */


/**
 * @param fd
 */
TcpConnection::TcpConnection(int fd) 
:m_sockIO(fd)
,m_socket(fd)
,m_local_addr(getLocalAddr())
,m_peer_addr(getPeerAddr())
{

}

string TcpConnection::streamToString(){
    ostringstream oss;
    oss<<m_local_addr.getIP()<<":"<<m_local_addr.getPort()<<"----->"
    <<m_peer_addr.getIP()<<":"<<m_peer_addr.getPort();
    return oss.str();
}

InetAddress TcpConnection::getLocalAddr(){
    struct sockaddr_in addr;
    socklen_t len = sizeof(sockaddr);
    int ret = getsockname(m_socket.getFd(),(struct sockaddr *)&addr,&len);
    if(ret == -1){
        perror("getsockname");
    }
    return InetAddress(addr);
}

InetAddress TcpConnection::getPeerAddr(){
    struct sockaddr_in addr;
    socklen_t len = sizeof(sockaddr);
    int ret = getpeername(m_socket.getFd(),(struct sockaddr *)&addr,&len);
    if(ret == -1){
        perror("getpeername");
    }
    return InetAddress(addr);
}

TcpConnection::~TcpConnection() {
    // close(m_socket.getFd());
}

/**
 * @return string
 */
string TcpConnection::receive() {
    char buf[65535] = {0};
    int len = m_sockIO.readline(buf,sizeof(buf));
    return string(buf,len);
}

/**
 * @param msg
 */
void TcpConnection::send(const string & msg) {
    m_sockIO.writen(msg.c_str(),msg.size());
}

Socket & TcpConnection::getSock(){
    return m_socket;
}